﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.SysEntity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace SysFrameWork
{
   public class UserBLL: PubMethods
    {
        Commands cmd;
        Tools.TxtLogHelper txt;
        OperateModel oper;
        ReturnResult rsl;
        LoginInfo userLogin;
        public UserBLL()
        {
            cmd = new Commands();
            txt = new Tools.TxtLogHelper();
            oper = new OperateModel();
            userLogin = new LoginInfo();
        }
        /// <summary>
        /// 获取用户列表(分页)
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public ReturnResult getUserPageList(string pageIndex, string pageSize, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_powerConfig_groups where groupName like '%管理员%'");
                var roleTable = cmd.GetDataTable(sb.ToString());//获取管理员角色
                var maxR = "undefined";
                if (roleTable.Rows.Count > 0)
                {
                    maxR = roleTable.Rows[0]["groupCode"].ToString();
                }

                sb.Clear();
                sb.Append(" isdel=0");
                if (userLogin.UserInfo().isAdmin != 1 && !userLogin.UserInfo().powerRole.Equals(maxR) )
                {//非管理员权限
                    sb.Append(" and createUser='" + userLogin.UserInfo().userCode + "'");
                }
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList("V_UserInfo", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 保存人员权限角色
       /// </summary>
       /// <param name="userCode"></param>
       /// <param name="groupCode"></param>
       /// <returns></returns>
        public ReturnResult SaveUserRole(string userCode,string groupCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbUser u = new DbUser();
                u.userCode = userCode;
                u.powerRole = groupCode;
                oper = new OperateModel();
                oper.Data = u;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "userCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 清除用户权限
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult cleanUserRole(string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbUser u = new DbUser();
                u.userCode = userCode;
                u.powerRole = "-";
                oper = new OperateModel();
                oper.Data = u;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "userCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 人员数据同步方法
       /// </summary>
       /// <param name="isAuto"></param>
       /// <returns></returns>
        public ReturnResult SyncUserData(bool isAuto = false)
        {
            rsl = new ReturnResult();
            SystemBLL sysBLL = new SystemBLL();
            OutBaseHelper cuHelper = new OutBaseHelper();
            var OperList = new List<OperateModel>();
            try
            {
                List<DbUser> UserList = new List<DbUser>();
                string baseCode = "";
                #region 账套选择
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                #endregion

                #region 同步用户信息
                StringBuilder sb = new StringBuilder();
                sb.Append("select Code, name,");
                //sb.Append(" cDept as dept,isnull(mobile,'') as uPhone,isStoped ");
                sb.Append(" isnull(mobile,'') as uPhone,isStoped ");
                sb.Append("from EAP_User where email is not null");
                var dt = cuHelper.getData(sb.ToString(), baseCode);//T+用户信息
                sb.Clear();
                sb.Append("select * from sys_users_info where 1=1 ");
                if (!string.IsNullOrWhiteSpace(baseCode))
                {
                    sb.Append(" and baseCode='" + baseCode + "' ");
                }
                var qTable = cmd.GetDataTable(sb.ToString());//获取所有人员信息

                string defaultPwd = Tools.ConfigReader.Reader["defaultPwd"];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        bool isAdd = true;
                        DbUser sys_User = new DbUser();
                        var oper = new OperateModel();
                        var arr = qTable.Select("userCode='" + dt.Rows[i]["Code"].ToString() + "'");
                        if (arr.Length > 0)
                        {
                            isAdd = false;
                        }
                        sys_User.userCode = dt.Rows[i]["Code"].ToString();
                        //if (dt.Rows[i]["dept"] != null && !string.IsNullOrWhiteSpace(dt.Rows[i]["dept"].ToString()))
                        //{
                        //    // sys_User.dept = dt.Rows[i]["dept"].ToString();//暂停
                        //}
                        sys_User.userName = dt.Rows[i]["name"].ToString();
                        sys_User.userPhone = dt.Rows[i]["uPhone"].ToString();
                        //是否是离职状态 
                        if (dt.Rows[i]["isStoped"].ToString() == "False")
                        {
                            sys_User.status = "Y";
                        }
                        else
                        {
                            sys_User.status = "N";
                        }
                        sys_User.isSync = "Y";
                        if (isAdd)
                        {
                            #region 添加方法
                            sys_User.userPwd = Tools.Encryption.DesEncrypt(defaultPwd);
                            sys_User.isAdmin = 0;
                            sys_User.isDel = 0;
                            sys_User.baseCode = baseCode;
                            sys_User.createTime = getNow();
                            if (isAuto)
                            {
                                sys_User.createUser = "admin";
                            }
                            else
                            {
                                sys_User.createUser = userLogin.UserInfo().userCode;
                            }
                            oper.Types = OperateModel.OperateType.Add;
                            #endregion
                        }
                        else
                        {
                            #region  修改方法
                            sys_User.isDel = 0;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "userCode";
                            #endregion
                        }
                        oper.Data = sys_User;
                        OperList.Add(oper);
          
                    }
                }
                #endregion

                rsl = cmd.MoreUpdate(OperList);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.ToString();
            }
            return rsl;
        }
        /// <summary>
        /// 同步部门信息
        /// </summary>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncDept(bool isAuto = false)
        {
            rsl = new ReturnResult();
            SystemBLL sysBLL = new SystemBLL();
            OutBaseHelper cuHelper = new OutBaseHelper();
            var OperList = new List<OperateModel>();
            try
            {
                List<DbUser> UserList = new List<DbUser>();
                string baseCode = "";
                #region 账套选择
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                #endregion

                StringBuilder sb = new StringBuilder();
                sb.Append("select code,name,depth,disabled from AA_Department");
                var dt = cuHelper.getData(sb.ToString(), baseCode);//T+部门信息
                sb.Clear();
                sb.Append("select * from sys_DepartMent_Info ");
                var qTable = cmd.GetDataTable(sb.ToString());//获取所有部门信息
                DbDeptInfo sys_dept;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sys_dept = new DbDeptInfo();
                    oper = new OperateModel();
                    var dr = qTable.Select("depCode='" + dt.Rows[i]["code"].ToString() + "'");
                    sys_dept.depName = dt.Rows[i]["name"].ToString();
                    sys_dept.parentsCode = dt.Rows[i]["depth"].ToString();
                    sys_dept.depCode = dt.Rows[i]["code"].ToString();
                    sys_dept.baseCode = baseCode;
                    if (dt.Rows[i]["disabled"].ToString()=="0")
                    {
                        sys_dept.status = "Y";
                    }
                    else
                    {
                        sys_dept.status = "N";
                    }
                    sys_dept.isSync = "Y";
                    sys_dept.isDel = 0;

                    if (dr.Length > 0)
                    {
                        //修改方法
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "depCode,baseCode";
                    }
                    else
                    {
                        #region  添加
                        sys_dept.createtime = getNow();
                        if (isAuto)
                        {
                            sys_dept.createuser = "admin";
                            sys_dept.baseCode = sysBLL.getDefaultBaseCode();
                        }
                        else
                        {
                            sys_dept.createuser = userLogin.UserInfo().userCode;
                            sys_dept.baseCode = userLogin.UserInfo().baseCode;
                        }
                        sys_dept.isSync = "Y";
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = sys_dept;
                    OperList.Add(oper);
                }
                if (OperList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(OperList);
                }
                else
                {
                    rsl.Message = "没有获取到要同步的数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        //public ReturnResult SyncUserData(bool isAuto = false)
        //{
        //    rsl = new ReturnResult();
        //    SystemBLL sysBLL = new SystemBLL();
        //    OutBaseHelper cuHelper = new OutBaseHelper();
        //    var OperList = new List<OperateModel>();
        //    try
        //    {
        //        List<DbUser> UserList = new List<DbUser>();
        //        string baseCode = "";
        //        #region 账套选择
        //        if (isAuto)
        //        {
        //            baseCode = sysBLL.getDefaultBaseCode();
        //        }
        //        else
        //        {
        //            baseCode = userLogin.UserInfo().baseCode;
        //        }
        //        #endregion

        //        #region 同步用户信息

        //        StringBuilder sb = new StringBuilder();

        //        sb.Append("select cPsn_Num as cPersonCode, cPsn_Name as cPersonName, ");
        //        sb.Append(" cDept_num as cDepCode,isnull(cPsnMobilePhone,'') as cPersonPhone, ");
        //        sb.Append(" rEmployState status ");
        //        sb.Append("from hr_hi_person");
        //        var dt = cuHelper.getData(sb.ToString(), baseCode);//U8用户信息
        //        sb.Clear();
        //        sb.Append("select * from sys_users_info where 1=1 ");
        //        if (!string.IsNullOrWhiteSpace(baseCode))
        //        {
        //            sb.Append(" and baseCode='" + baseCode + "' ");
        //        }
        //        var qTable = cmd.GetDataTable(sb.ToString());//获取所有人员信息

        //        string defaultPwd = Tools.ConfigReader.Reader["defaultPwd"];
        //        if (dt.Rows.Count > 0)
        //        {
        //            for (int i = 0; i < dt.Rows.Count; i++)
        //            {
        //                bool isAdd = true;
        //                DbUser sys_User = new DbUser();
        //                var oper = new OperateModel();
        //                var arr = qTable.Select("userCode='" + dt.Rows[i]["cPersonCode"].ToString() + "'");
        //                if (arr.Length > 0)
        //                {
        //                    isAdd = false;
        //                }
        //                sys_User.userCode = dt.Rows[i]["cPersonCode"].ToString();
        //                sys_User.dept = dt.Rows[i]["cDepCode"].ToString();
        //                sys_User.userName = dt.Rows[i]["cPersonName"].ToString();
        //                sys_User.userPhone = dt.Rows[i]["cPersonPhone"].ToString();
        //                //是否是离职状态 
        //                if (dt.Rows[i]["status"].ToString() == "10")
        //                {
        //                    sys_User.status = "Y";
        //                }
        //                else
        //                {
        //                    sys_User.status = "N";
        //                }
        //                sys_User.isSync = "Y";
        //                if (isAdd)
        //                {
        //                    #region 添加方法
        //                    sys_User.userPwd = Tools.Encryption.DesEncrypt(defaultPwd);
        //                    //sys_User.isSync = "Y";
        //                    sys_User.isAdmin = 0;
        //                    sys_User.isDel = 0;
        //                    sys_User.baseCode = baseCode;
        //                    sys_User.createTime = getNow();
        //                    if (isAuto)
        //                    {
        //                        sys_User.createUser = "admin";
        //                    }
        //                    else
        //                    {
        //                        sys_User.createUser = userLogin.UserInfo().userCode;
        //                    }
        //                    oper.Types = OperateModel.OperateType.Add;
        //                    #endregion
        //                }
        //                else
        //                {
        //                    #region  修改方法
        //                    sys_User.isDel = 0;
        //                    oper.Types = OperateModel.OperateType.Edit;
        //                    oper.Conditions = "userCode";
        //                    #endregion
        //                }
        //                oper.Data = sys_User;
        //                OperList.Add(oper);

        //            }
        //        }
        //        #endregion

        //        #region 同步部门信息
        //        sb.Clear();
        //        sb.Append("select  cdepcode,cdepname,idepgrade,dDepEndDate from department");
        //        dt = cuHelper.getData(sb.ToString(), baseCode);//U8部门信息
        //        sb.Clear();
        //        sb.Append("select * from sys_DepartMent_Info ");
        //        qTable = cmd.GetDataTable(sb.ToString());//获取所有部门信息
        //        DbDeptInfo sys_dept;
        //        if (dt.Rows.Count > 0)
        //        {
        //            for (int i = 0; i < dt.Rows.Count; i++)
        //            {
        //                sys_dept = new DbDeptInfo();
        //                oper = new OperateModel();
        //                var dr = qTable.Select("depCode='" + dt.Rows[i]["cdepcode"].ToString() + "'");
        //                sys_dept.depName = dt.Rows[i]["cdepname"].ToString();
        //                sys_dept.parentsCode = dt.Rows[i]["idepgrade"].ToString();
        //                sys_dept.depCode = dt.Rows[i]["cdepcode"].ToString();
        //                sys_dept.baseCode = baseCode;
        //                if (string.IsNullOrWhiteSpace(dt.Rows[i]["dDepEndDate"].ToString()))
        //                {
        //                    sys_dept.status = "Y";
        //                }
        //                else
        //                {
        //                    sys_dept.status = "N";
        //                }
        //                if (dr.Length > 0)
        //                {
        //                    //修改方法
        //                    oper.Types = OperateModel.OperateType.Edit;
        //                    oper.Conditions = "depCode,baseCode";
        //                }
        //                else
        //                {
        //                    #region  添加
        //                    sys_dept.baseCode = userLogin.UserInfo().baseCode;
        //                    sys_dept.createtime = getNow();
        //                    if (isAuto)
        //                    {
        //                        sys_dept.createuser = "admin";
        //                    }
        //                    else
        //                    {
        //                        sys_dept.createuser = userLogin.UserInfo().userCode;
        //                    }
        //                    sys_dept.isSync = "Y";
        //                    oper.Types = OperateModel.OperateType.Add;
        //                    #endregion
        //                }
        //                oper.Data = sys_dept;
        //                OperList.Add(oper);
        //            }
        //        }
        //        #endregion

        //        rsl = cmd.MoreUpdate(OperList);

        //    }
        //    catch (Exception ex)
        //    {
        //        rsl.Message = ex.ToString();
        //    }
        //    return rsl;
        //}
        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult AddUser(string jsonStr)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                var user = JsonConvert.DeserializeObject<DbUser>(jsonStr);
                if (string.IsNullOrWhiteSpace(user.userCode))
                {
                    rsl.Message = "登录账号不允许为空";
                    return rsl;
                }
                //if (string.IsNullOrWhiteSpace(user.dept))
                //{
                //    rsl.Message = "部门信息不允许为空";
                //    return rsl;
                //}
                string sql = "select * from sys_users_info where userCode='" + user.userCode + "'";
                var table = cmd.GetDataTable(sql);

                OperateModel oper = new OperateModel();
                List<OperateModel> list = new List<OperateModel>();
                if (user.id != null && user.id > 0)
                {
                    #region 修改数据
                    foreach (DataRow r in table.Rows)
                    {
                        if (r["id"].ToString() != user.id.ToString().Trim())
                        {
                            rsl.Message = string.Format("账号已存在：{0}", user.userCode);
                            return rsl;
                        }
                    }
                    #endregion
                    oper.Data = user;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    list.Add(oper);
                }
                else
                {
                    #region 添加数据
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = string.Format("账号已存在：{0}", user.userCode);
                        return rsl;
                    }

                    user.status = "Y";
                    user.isSync = "N";
                    user.isAdmin = 0;
                    user.isDel = 0;
                    user.baseCode = userLogin.UserInfo().baseCode;
                    user.createUser = userLogin.UserInfo().userCode;
                    user.createTime = DateTime.Now.ToString();
                    user.userPwd = Tools.Encryption.DesEncrypt(Tools.ConfigReader.Reader["defaultPwd"].ToString()); ;
                    oper.Data = user;
                    oper.Types = OperateModel.OperateType.Add;
                    list.Add(oper);
                    #endregion
                }
                rsl = cmd.MoreUpdate(list);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="userCode">系统账号</param>
        /// <returns></returns>
        public ReturnResult reSetPwd(string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    rsl.Result = false;
                    rsl.Message = "用户账号不能为空";
                    return rsl;
                }
                string sql = "select * from sys_users_info where userCode='" + userCode + "'";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count < 1)
                {
                    rsl.Result = false;
                    rsl.Message = "无法获取账号信息";
                    return rsl;
                }
                var pwd = Tools.Encryption.DesEncrypt(Tools.ConfigReader.Reader["defaultPwd"].ToString());
                StringBuilder sb = new StringBuilder();
                sb.Append("update  sys_users_info  set  userPwd='" + pwd + "' ");
                sb.Append(" where id=" + table.Rows[0]["id"].ToString() + "");
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldpwd"></param>
        /// <param name="newpwd"></param>
        /// <returns></returns>
        public ReturnResult ChanagePWD(string oldpwd, string newpwd)
        {
            ReturnResult rsl = new ReturnResult();
            Tools.Encryption sec = new Tools.Encryption();
            try
            {
                string enpwd = Tools.Encryption.DesEncrypt(oldpwd);
                var jmpwd = Tools.Encryption.DesEncrypt(newpwd);
                string userCode = userLogin.UserInfo().userCode;
                string sql = "select * from sys_users_info where userCode='" + userCode + "'";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "无法获取账号信息";
                    return rsl;
                }
                if (table.Rows[0]["userPwd"].ToString() != enpwd)
                {
                    rsl.Message = "当前密码输入错误";
                    return rsl;
                }
                sql = "update sys_users_info set userPwd='" + jmpwd + "',openpwd='" + jmpwd + "' where userCode='" + userCode + "'";
                rsl = cmd.UpdateSql(sql);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult DelUserInfo(string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbUser user = new DbUser();
                user.isDel = 1;
                user.userCode = userCode;
                user.delUser = userLogin.UserInfo().userCode;
                user.delTime = getNow();
                oper = new OperateModel();
                oper.Data = user;
                oper.Conditions = "userCode";
                oper.Types = OperateModel.OperateType.Edit;
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 根据用户编码获取人员信息
        /// </summary>
        /// <param name="usCode">用户编码</param>
        /// <returns></returns>
        public ReturnResult getUserInfoByCode(string usCode, string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_users_info where ");
                if (!string.IsNullOrWhiteSpace(dataId))
                {
                    sb.Append("id=" + dataId);
                }
                else if (!string.IsNullOrWhiteSpace(usCode))
                {
                    sb.Append("userCode=" + usCode);
                }
                else
                {
                    sb.Append("1>2");
                }

                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.ToString();
            }
            return rsl;
        }
        /// <summary>
        /// 获取全部有效的用户数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult AllUserList(string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_UserInfo where status='Y'");
                sb.Append(" and isdel=0 and baseCode='" + userLogin.UserInfo().baseCode + "'");
                sb = CreateSelectCondition(sb, condition);
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
